'use strict';
//配送订单列表
import React,{Component} from 'react';
import Header from '../../common/header';
import * as URLconstant from '../../constant/URLconstant'
import Util from '../../common/util';
import OrderDetail from './orderDetail';
import Toast from '../../common/ToastUtil';
import Modal from 'react-native-modalbox';
import {
    View,
    Text,
    TouchableOpacity,
    Image,
    StyleSheet,
    ScrollView, ListView,
    Alert, Linking
} from 'react-native';
export default class orderList extends Component{
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            orderName: [{'name': '全部订单','status': '0'}, {'name': '待配货','status': '5'}, {'name': '待配送','status': '1'
            }, {'name': '配送中','status': '3'}, {'name': '已完成','status': '4'}],
            loaded:true,
            dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
            dataSource: [],
            page:1,
            isOver:false,
            again:true,
            orderStatus:this.props.delivery_status?this.props.delivery_status:0,
            orderCode:'',
            isOpen:false,
            isContactOpen:false,
            qq:[]
        };
        this.onEndReached=this.onEndReached.bind(this)
          this._renderRow=this._renderRow.bind(this)
          this.renderFooter=this.renderFooter.bind(this)
      }

    componentDidMount() {
          LOG('code_type======'+111)
        this.getOrderList()
        this.getContact()
    }


    getContact(){
        let url = URLconstant.GET_CONTACT
        let datakey=[]
        Util.get(url,datakey,this.getContactSuc.bind(this),this.errorCallback.bind(this))
    }

    getContactSuc(datas){
         let qq = datas.data.qq
        if(qq.length!=0&&qq[0]!=''){
             this.setState({
                 qq:datas.data.qq
             })
        }
        this.setState({
            phone_400:datas.data.phone_400,

        })
    }


      getOrderList(){
          let url = URLconstant.GET_ORDER_LIST
          let datakey=[]
          if(this.props.order_sn){
              datakey['delivery_order_sn']=this.props.order_sn
          }
          datakey['page'] = this.state.page;
          datakey['delivery_status'] = this.state.orderStatus;
          datakey['user_id'] = this.props.user_id;
          datakey['order_type'] = this.props.order_type;
          datakey['role_id'] = this.props.role_id;
          datakey['shop_id'] = this.props.shop_id;
          Util.get(url,datakey,this.getOrderListSuc.bind(this),this.errorCallback.bind(this))
      }

    getOrderListSuc(datas){
        LOG('code_type======'+datas.status)
        if(datas.status==0){
            let isOver = false
            let again = true
            let page = this.state.page
            let newList = datas.data.list
            let total = datas.data.total
            let oldDatas = this.state.dataSource;
            if(newList.length<10){
                isOver=true
                again=false
            }
            Array.prototype.push.apply(oldDatas, newList);
            this.setState({
                isOver:isOver,
                dataSource2: this.state.dataSource2.cloneWithRows(oldDatas),
                dataSource: oldDatas,
                loaded:false,
                page:page+1,
                again:again
            })
        }
    }

    errorCallback(err){

    }

    async selectStatus(status){
         await this.setState({
             dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
             dataSource: [],
             page:1,
             isOver:false,
             again:true,
             orderStatus:status,
             loaded:true
          })
        this.getOrderList()
    }

    onEndReached(){
        let again = this.state.again
        if(again){
            this.getOrderList()
        }
    }

    toOrderDetail(order_id,order_sn){
          this.props.navigator.push({
              component:OrderDetail,
              passProps:{
                  order_id:order_id,
                  order_sn:order_sn,
                  user_id:this.props.user_id
              }
          })
    }

    _renderRow(item){
        return(
            <View key={item.order_id} style={styles.order_item}>
                <View style={styles.order_header}>
                    <Text style={{fontSize:16,color:"#000",marginBottom:5}}>店铺:{item.seller_name}</Text>
                    <View style={styles.rows_view}>
                        <Text style={{fontSize:12,color:"#969696"}}>订单号:{item.order_sn}</Text>
                        {
                            item.delivery_status!=0?
                                <View style={styles.type_box}>
                                    <Text style={{fontSize:12,color:"#e7393c"}}>极速配送</Text>
                                </View>:
                                null
                        }

                    </View>
                </View>
                <TouchableOpacity onPress={()=>this.toOrderDetail(item.order_id,item.order_sn)}>
                    {
                        item.order_goods.map((goods,index)=>{
                           return(
                               <View style={styles.goods_item} key={index}>
                                    <Image
                                        source={{uri:goods.goods_image}}
                                        resizeMode={'cover'}
                                        style={{width:85,height:85,}}
                                    />
                                   <View style={styles.goods_item_right}>
                                       <View>
                                           <Text style={{fontSize:15,color:"#333"}}>{goods.goods_name}</Text>
                                           <Text style={{fontSize:12,color:"#969696"}}>{goods.specification}</Text>
                                           <View style={styles.rows_view}>
                                               {
                                                   goods.quantity>goods.stock?
                                                       <Text style={{fontSize:12,color:"#f00",marginRight:10}}>(库存不足)</Text>:
                                                       null
                                               }
                                               {
                                                   goods.if_show==0?
                                                       <Text style={{fontSize:12,color:"#f00"}}>(已下架)</Text>:
                                                       null
                                               }
                                           </View>
                                       </View>
                                       <View style={styles.rows_view}>
                                           <Text style={{fontSize:14,color:"#333"}}>单价:</Text>
                                           <Text style={{fontSize:15,color:"#f00",marginLeft:5}}>¥{goods.price}</Text>
                                       </View>
                                   </View>
                               </View>
                           )
                        })
                    }
                </TouchableOpacity>
                <View style={styles.goods_total_wrap}>
                    <View style={[styles.rows_view,{marginBottom:5}]}>
                        <Text style={{fontSize:14,color:"#666"}}>共 {item.total} 件商品，合计</Text>
                        <Text style={{fontSize:14,color:"#f00"}}>¥{item.order_amount}</Text>
                    </View>
                    <View style={styles.rows_view}>
                        <Text style={{fontSize:12,color:"#aaa"}}>(含运费¥{item.shipping_fee}</Text>
                        {item.coupon_fee>0?<Text style={{fontSize:12,color:"#aaa"}}> -优惠券¥{item.coupon_fee}</Text>:null}
                        {item.surplus_money>0?<Text style={{fontSize:12,color:"#aaa"}}> -余额¥{item.surplus_money}</Text>:null}
                        {item.adjust_goods_fee>0?<Text style={{fontSize:12,color:"#aaa"}}> -后台调整价格¥{item.adjust_goods_fee}</Text>:null}
                        <Text style={{fontSize:12,color:"#aaa"}}>)</Text>
                    </View>
                </View>
                <View style={styles.goods_state}>
                    {this.backBtn(item.delivery_status,item.order_sn)}
                </View>
            </View>
        )
    }

    backBtn(delivery_status,order_sn){
          let role_id = this.props.role_id
        let identity_id = this.props.identity_id
        if(delivery_status==1){
            if(role_id==8||identity_id==8){
                return(
                    <TouchableOpacity style={styles.opera_btn} onPress={()=>this.startDelivery(order_sn,3)}>
                        <Text style={{fontSize:14,color:"#fff"}}>开始配送</Text>
                    </TouchableOpacity>
                )
            }else{
                return(
                    <TouchableOpacity style={styles.opera_btn} onPress={()=>this.getOrderCode(order_sn,1,delivery_status)}>
                        <Text style={{fontSize:14,color:"#fff"}}>配送二维码</Text>
                    </TouchableOpacity>
                )
            }
        }else if(delivery_status==3){
            if(role_id==8||identity_id==8){
                return(
                    <TouchableOpacity style={styles.opera_btn} onPress={()=>this.getOrderCode(order_sn,2,delivery_status)}>
                        <Text style={{fontSize:14,color:"#fff"}}>到货二维码</Text>
                    </TouchableOpacity>
                )
            }else{
                return(
                    <Text style={{fontSize:14,color:"#666"}}>配货完成，已交接配送员</Text>
                )
            }
        }else if(delivery_status==4){
            return(
                <Text style={{fontSize:14,color:"#666"}}>配送完成，已交货给客户</Text>
            )
        }else {
            if(role_id==8){
                return  <Text style={{fontSize:14,color:"#666"}}>该订单未配货，请稍后</Text>
            }else if(role_id==2){
                return <Text style={{fontSize:14,color:"#666"}}>门店店员未进行配货</Text>
            }else {
                return(
                    <TouchableOpacity style={styles.opera_btn} onPress={()=>this.prepareSuc(order_sn,1)}>
                        <Text style={{fontSize:14,color:"#fff"}}>配货完成</Text>
                    </TouchableOpacity>
                )
            }
        }
    }

    //配货完成
    prepareSuc(order_sn,status){
          Alert.alert(
              '配货提示',
              '是否确认配货已完成，可以开始配送',
              [
                  {text:'取消',onPress:()=>LOG('press cancel')},
                  {text:'确定', onPress:()=>this.changeOrderStatus(order_sn,status)}
              ]
          )
    }

    //开始配送
    startDelivery(order_sn,status){
          Alert.alert(
              '配送提示',
              "是否确认配货已完成，可以开始配送",
              [
                  {text:'取消',onPress:()=>LOG('press cancel')},
                  {text:'确定', onPress:()=>this.changeOrderStatus(order_sn,status)}
              ]
          )
    }

    changeOrderStatus(order_sn,status){
        let url = URLconstant.CHANGE_ORDER_STATUS
        let datakey=[]
        datakey['user_id'] = this.props.user_id;
        datakey['order_sn'] = order_sn;
        datakey['delivery_status'] = status;
        Util.get(url,datakey,async (datas)=>{
            Toast.show(datas.msg)
            if(datas.status==1){
                await this.setState({
                    dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
                    dataSource: [],
                    page:1,
                    isOver:false,
                    again:true,
                    loaded:true,
                    orderStatus:status
                })
                this.getOrderList()
            }
        },this.errorCallback.bind(this))
    }

    async changeOrderStatusSuc(datas){
          LOG('datas==='+JSON.stringify(datas))
    }

    callPhone(url){
        if(!url){
            Toast.show('联系方式不能为空，请联系后台管理员')
            return false
        }else{
            url='tel:'+url
            Linking.canOpenURL(url).then(supported => {
                if (!supported) {
                    Toast.show('不支持拨打该联系方式')
                } else {
                    return Linking.openURL(url);
                }
            }).catch(err => Toast.show('错误的联系方式'));
        }
    }

    openQQ(qq){
        if(qq==''){
            Toast.show('联系QQ不能为空，请联系后台管理员')
            return false
        }
        Util.openQQ(qq)
    }

    getOrderCode(order_sn,type,delivery_status){
          this.setState({
              showType:type
          })
        let url
        let datakey=[]
        if(type==1){
            url = URLconstant.GET_ORDER_CODE
        }else {
            url=URLconstant.GET_DELIVERY_ORDER
            datakey['path'] = 'pages/orderList/orderList?iscode=1&order_sn=' + order_sn;
            datakey['iscode'] = 1
        }
        datakey['order_sn']=order_sn
        datakey['user_id']=this.props.user_id
        this.order_sn=order_sn
        this.order_type=type
        this.delivery_status=delivery_status
        Util.get(url,datakey,this.getCodeSuc.bind(this),this.errorCallback.bind(this))
    }

    getCodeSuc(datas){
          if(datas.status==0){
              this.setState({
                  isOpen:true,
                  orderCode:datas.data
              })
          }else{
              Toast.show(datas.msg)
          }
    }



    renderFooter(){
        return (
            <View style={{height:30,alignItems:'center',justifyContent:'center'}}>
                <Text style={{fontSize:12,color:"#969696"}}>{this.state.isOver?"没有更多数据了":"正在加载中"}</Text>
            </View>
        )
    }

    showContactModal(){
        return(
            <Modal
                isOpen={this.state.isContactOpen}
                backdropPressToClose={false} swipeToClose={false}
                style={styles.contact_modal}
            >
                <View style={styles.modal_header}>
                    <Text style={{fontSize:14,color:"#333"}}>联系卖家</Text>
                    <TouchableOpacity style={styles.close_btn} onPress={()=>this.setState({
                        isContactOpen:false
                    })}>
                        <Image
                            source={require('../../imgs/close.png')}
                            resizeMode={'cover'}
                            style={{width:20,height:20}}
                        />
                    </TouchableOpacity>
                </View>
                <View style={styles.contact_item}>
                    <View style={styles.contact_left}>
                        <Text style={{fontSize:12,color:"#333"}}>联系方式</Text>
                    </View>
                    <View style={styles.contact_center}>
                        <Text>{this.state.phone_400}</Text>
                    </View>
                    <TouchableOpacity onPress={()=>this.callPhone(this.state.phone_400)} style={styles.contact_right}>
                        <Text style={{fontSize:12,color:"#fff"}}>拨打电话</Text>
                    </TouchableOpacity>
                </View>
                {
                    this.state.qq[0]==''||this.state.qq.length==0?
                        null:
                        <View>
                            {
                                this.state.qq.map((item,index)=>{
                                    return(
                                        <View key={index} style={styles.contact_item}>
                                            <View style={styles.contact_left}>
                                                <Text style={{fontSize:12,color:"#333"}}>联系QQ</Text>
                                            </View>
                                            <View style={styles.contact_center}>
                                                <Text>{item}</Text>
                                            </View>
                                            <TouchableOpacity onPress={()=>this.openQQ(item)} style={styles.contact_right}>
                                                <Text style={{fontSize:12,color:"#fff"}}>打开QQ</Text>
                                            </TouchableOpacity>
                                        </View>
                                    )
                                })
                            }
                        </View>
                }

            </Modal>
        )
    }

    refreshOrder(){
        let url = URLconstant.GET_ORDER_STATUS
        let datakey=[]
        datakey['user_id']=this.props.user_id
        datakey['order_sn'] = this.order_sn
        Util.get(url,datakey,async (datas)=>{
            if(datas.status==0){
                let tips
                let status
                if(this.order_type==1){
                    tips='配送员还没确认收到货物'
                    status=3
                }else{
                    tips='客户还没确认收到货物'
                    status=4
                }
                if(this.delivery_status==datas.data.delivery_status){
                    Toast.show(tips)
                }else{
                    await this.setState({
                        dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
                        dataSource: [],
                        page:1,
                        isOver:false,
                        again:true,
                        loaded:true,
                        orderStatus:status,
                        isOpen:false
                    })
                    this.getOrderList()
                }
            }
        },this.errorCallback.bind(this))
    }

      render(){
          return(
              <View style={{flex:1,backgroundColor:"#f0f0f0"}}>
                  <Header navigator={this.props.navigator} initObj={{ title: '配送订单管理',id:2}}/>
                  <View style={styles.header_view}>
                      {
                          this.state.orderName.map((item,index)=>{
                              return(
                                  <TouchableOpacity onPress={()=>this.selectStatus(item.status)} style={styles.header_item} key={index}>
                                      <Text style={item.status==this.state.orderStatus?{fontSize:14,color:"#f00"}:{fontSize:14,color:"#696969"}}>{item.name}</Text>
                                  </TouchableOpacity>
                              )
                          })
                      }
                  </View>
                  {
                      this.state.loaded?
                          <View style={{flex:1,}}>
                              {Util.loading()}
                          </View>:
                          <View style={{flex:1}}>
                              {
                                  this.state.dataSource.length==0?
                                      <View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
                                          <Text>没有订单</Text>
                                      </View>:
                                      <ListView
                                          dataSource={this.state.dataSource2}
                                          onEndReached={this.onEndReached}
                                          renderRow={this._renderRow}
                                          renderFooter={this.renderFooter}
                                      />
                              }
                          </View>
                  }
                  <Modal
                      isOpen={this.state.isOpen} position={'center'} style={styles.code_modal}
                      onClosed={()=>this.setState({isOpen:false})}
                  >
                      <Image
                          source={{uri:this.state.orderCode}}
                          resizeMode={'cover'}
                          style={{width:300,height:300}}
                      />
                        <View style={styles.modal_txt_view}>
                            <Text style={{fontSize:16,color:"#696969",textAlign:'center'}}>{this.state.showType==1?"请将二维码向配送员展示并由配送员扫码确认开始送货":"请将二维码向订单客户展示并由客户扫码确认收货"}</Text>
                        </View>
                      <View style={{alignItems:'center',justifyContent:'center',marginTop:10}}>
                          <TouchableOpacity
                              onPress={()=>this.refreshOrder()}
                              style={{width:200,height:40,alignItems:'center',justifyContent:'center',borderRadius:5,backgroundColor:"#f65061"}}>
                              <Text style={{fontSize:14,color:"#fff"}}>刷新订单状态</Text>
                          </TouchableOpacity>
                      </View>
                  </Modal>
                  {this.showContactModal()}
              </View>
          )
      }
}
var styles = StyleSheet.create({
    header_view:{
        backgroundColor:"#fff",
        flexDirection:'row',
        marginBottom:10
    },
    header_item:{
        flex:1,
        alignItems:'center',
        justifyContent:'center',
        height:45
    },
    order_item:{
        backgroundColor:"#fff",
        marginBottom:10,
        padding:5,
    },
    order_header:{
        borderBottomWidth:1,
        borderBottomColor:"#e0e0e0",
        paddingBottom:5
    },
    rows_view:{
        flexDirection:'row',
        alignItems:'center'
    },
    type_box:{
        borderWidth:1,
        borderColor:"#e7393c",
        alignItems:'center',
        justifyContent:'center',
        paddingHorizontal:5,
        height:20,
        borderRadius:5,
        marginLeft:5
    },
    goods_item:{
        paddingVertical:7,
        flexDirection:'row'
    },
    goods_item_right:{
        flex:1,
        justifyContent:'space-between',
        paddingLeft:10,
        height:85,
        flexWrap:'wrap'
    },
    goods_total_wrap:{
        alignItems:'flex-end',
        borderTopWidth:1,
        borderTopColor:"#e0e0e0",
        paddingVertical:7
    },
    goods_state:{
        alignItems:'flex-end',
        borderTopWidth:1,
        borderTopColor:"#e0e0e0",
        height:40,
        justifyContent:'center'
    },
    opera_btn:{
        paddingHorizontal:10,
        height:26,
        borderRadius:5,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:"#e7393c",
    },
    code_modal:{
        width:300,
        height:430,
        alignItems:'center',
        justifyContent:'center'
    },
    modal_txt_view:{
        alignItems:'center',
        justifyContent:'center',
        width:200,
    },
    contact_modal:{
        width:300,
        height:300,
        borderRadius:5,
    },
    modal_header:{
        height:40,
        alignItems:'center',
        justifyContent:'center',
        borderBottomWidth:1,
        borderBottomColor:"#e0e0e0"
    },
    contact_item:{
        flexDirection:"row",
        height:50,
        alignItems:'center',
        paddingHorizontal:15,
    },
    contact_left:{
        width:70,
    },
    contact_center:{
        flex:1
    },
    contact_right:{
        width:60,
        height:20,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:"#f65061",
        borderRadius:4
    },
    close_btn:{
        position:'absolute',
        top:10,
        right:5,
    }
})